package com.means.polymerize.core.terminal.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.jcraft.jsch.Channel;
import com.means.polymerize.common.constants.Global;
import com.means.polymerize.core.terminal.common.lang.ChannelStorageContainer;
import com.means.polymerize.core.terminal.common.lang.SessionStorageContainer;
import com.means.polymerize.core.terminal.common.util.SshUtil;
import com.means.polymerize.core.terminal.modal.entity.TerminalConnectInfoReceive;
import com.means.polymerize.core.terminal.service.TerminalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * The type Terminal service.
 *
 * @author xuhiafneg
 * @date 2021.05.09
 */
@Slf4j
@Service
@SuppressWarnings("AlibabaSwitchStatement")
public class TerminalServiceImpl implements TerminalService {

    @Override
    public void reachEcho(String token, String executor) {
        final TerminalConnectInfoReceive receive = JSON.parseObject(executor, TerminalConnectInfoReceive.class);
        switch (receive.getOperate()) {
            /* 连接操作 */
            case Global.TERMINAL_OPERATE_CONNECT -> ThreadUtil.execAsync(() -> SshUtil.connectSsh(token, receive));
            /* 命令操作  */
            case Global.TERMINAL_OPERATE_COMMAND -> {
                final Channel channel = ChannelStorageContainer.getChannel(token);
                if (Objects.nonNull(channel)) {
                    SshUtil.sendSshCommand(channel, receive.getCommand());
                } else {
                    closeSessionConnection(token);
                }
            }
            default -> closeAllConnection(token);
        }
    }

    @Override
    public void closeChannelConnection(String token) {
        final Channel channel = ChannelStorageContainer.getChannel(token);
        if (Objects.nonNull(channel)) {
            channel.disconnect();
            ChannelStorageContainer.removeChannel(token);
        }
    }

    @Override
    public void closeSessionConnection(String token) {
        if (Objects.nonNull(token)) {
            SessionStorageContainer.getSessions(token).closeSession();
            SessionStorageContainer.removeSessions(token);
        }
    }

    @Override
    public void closeAllConnection(String token) {
        closeChannelConnection(token);
        closeSessionConnection(token);
    }
}
